﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace TFSVSAddin
{
    public partial class ImportLinks : Form
    {
        public ImportLinks()
        {
            InitializeComponent();
        }

        public WorkItemStore WorkItemStore { get; set; }

        private void ImportLinks_Load(object sender, EventArgs e)
        {
            foreach (var lt in this.WorkItemStore.WorkItemLinkTypes.LinkTypeEnds)
            {
                linkTypeComboBox.Items.Add(lt.Name);
            }
        }

        private void importButton_Click(object sender, EventArgs e)
        {
            Dictionary<int, WorkItem> saveList = new Dictionary<int, WorkItem>();
            WorkItemLinkTypeEnd linkTypeEnd = this.WorkItemStore.WorkItemLinkTypes.LinkTypeEnds[linkTypeComboBox.Text];
            foreach (string line in idsTextBox.Lines)
            {
                string[] ids = line.Split(new char[] { ' ', ',', ';', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                int a = -1;
                int b = -1;
                if (ids.Length < 2)
                    continue;
                if (!int.TryParse(ids[0], out a))
                    continue;
                if (!int.TryParse(ids[1], out b))
                    continue;

                WorkItem wiA;
                if (saveList.ContainsKey(a))
                    wiA = saveList[a];
                else
                    wiA = this.WorkItemStore.GetWorkItem(a);

                bool linkExists = false;
                foreach (WorkItemLink l in wiA.WorkItemLinks)
                {
                    if (l.LinkTypeEnd.Name != linkTypeEnd.Name)
                        continue;
                    if (l.SourceId != a)
                        continue;
                    if (l.TargetId != b)
                        continue;
                    linkExists = true;
                    break;
                }
                if (linkExists)
                    continue;
                wiA.Links.Add(new RelatedLink(linkTypeEnd, b));
                if (!saveList.ContainsKey(a))
                    saveList.Add(a, wiA);
            }
            WorkItem[] saveArray = new WorkItem[saveList.Count];
            saveList.Values.CopyTo(saveArray, 0);
            this.WorkItemStore.BatchSave(saveArray, SaveFlags.MergeLinks);
            MessageBox.Show("Saved " + saveList.Count + " WorkItems");
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
